package com.tanhua.sso.controller;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: you
 * @Date: 2021/05/25/15:18
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;


    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> map) {
        try {
            //获取请求体中传递过来的手机号、验证码
            String phone = map.get("phone");
            String code = map.get("verificationCode");

            String data = userService.login(phone, code);

            //登录成功
            if (StringUtils.isNotEmpty(data)) {
                String[] split = StringUtils.split(data,"|");
                //String，Object
                HashMap<String, Object> result = new HashMap<>();
                result.put("token", split[0]);
                System.out.println(data);
                System.out.println(split[0]);
                System.out.println(split[1]);
                //注意返回值isNew 是布尔类型，需要转换
                result.put("isNew", Boolean.valueOf(split[1]));


                System.out.println("登录成功"+phone);
                return ResponseEntity.ok(result);


            }
        } catch (Exception e) {
            log.error("用户登录失败", e);
        }

        //登录失败，返回相应的错误信息
        ErrorResult errorResult = ErrorResult.builder().errCode("000004").errMessage("登录失败").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }


//    @GetMapping("{token}")     //@PathVariable ：获取到url路径中的值 即http://ip:端口号/user/值（token）
//    public User checkToken(@PathVariable("token") String token){
//        return  userService.queryUserByToken(token);
//    }

    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
